<?php

namespace Home\Controller;

use Think\Controller;

class BBSinvitController extends Controller
{
	//帖子详情页
	public function BBSinvit()
	{

		$init = M('invitation');
		$user = M('user');
		$type = M('type');
		$com = M('comment');
		$rep = M('replay');
		$inid = I('get.inid/d');
		//分页
		$count = $com->field(array('user.username','user.userimage','user.score','user.uid','comment.uid'=>'cuid','comment.cid','comment.ctext','comment.ctime'))->table(array('bbs_user'=>'user','bbs_comment'=>'comment'))->where(' comment.uid=user.uid and comment.inid='.$inid)->count();
		$Page = new \Think\Page($count,3);
		//查询帖子信息
		$InitData = $init->where('inid='.$inid)->find();
		$init->where('inid='.$inid)->setInc('inpv',1);//帖子浏览量+1
		//查询楼主信息
		$UserData = $user->where('uid='.$InitData['uid'])->find();
		//查询二级分类名
		$TypeData02 = $type->where('tid='.$InitData['pid'])->find();
		//查询一级分类名
		$TypeData01 = $type->where('tid='.$TypeData02['fid'])->find();
		
		//查询有关于这个帖子的所有评论以及评论者信息 按照评论时间升序排序
		$ComData = $com->field(array('user.username','user.userimage','user.score','user.uid','comment.uid'=>'cuid','comment.cid','comment.ctext','comment.ctime'))->table(array('bbs_user'=>'user','bbs_comment'=>'comment'))->where(' comment.uid=user.uid and comment.inid='.$inid)->limit($Page->firstRow.','.$Page->listRows)->order('comment.ctime')->select();
		//查询帖子下面的回复(是帖子下面的回复，不是评论，按照cid为0条件存储的)
		$initRep = $rep->where('cid=0 and inid='.$inid)->select();
		//构造二维数组，将每一层评论下的回复添加进其二维数组中
		foreach ($ComData as $key => $value) {
			$ComData[$key]['replay'] = $rep->where("cid={$value['cid']}")->select();
		}
		
		$show = $Page->show();// 分页显示输出
		$this->assign('page',$show);// 赋值分页输出
		$this->assign('InitData',$InitData);
		$this->assign('UserData',$UserData);
		$this->assign('TypeData01',$TypeData01);
		$this->assign('TypeData02',$TypeData02);
		$this->assign('ComData',$ComData);
		$this->assign('initRep',$initRep);
		$this->display('BBSinvit/BBSinvit');
	}

	public function BBSinvitAddView()
	{
		if(empty($_SESSION)){
			$this->error('请先登录');
		}
		
		$this->display('BBSinvit/BBSinvitAddView');

	}
	//添加帖子
	public function BBSinvitAdd()
	{
		if(empty($_SESSION)){
			$this->error('请先登录');
		}
		$type = M('invitation');
		$_POST['intime'] = time();
		//初始化数据
		if(!$type->create()){
			$this->error($this->_model->getError());
			exit;
		}
		
		//执行添加
		if($type->add()>0){
			$this->success("添加成功!",U('Index/bbsIndex'));
		}else{
			$this->error("添加失败",U('BBSinvit/BBSinvitAddView'));
		}
	}
	//分类联动
	public function BBSinvitAjax()
	{
		$type = M('type');
		//接收查询条件
    	$fid = empty($_GET['fid'])?0:$_GET['fid'];
    	$data = $type->where('fid='.$fid)->select();

    	//echo json_encode($data);
    	$this->ajaxReturn($data);
	}

}